import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Form,
  Input,
  Button,
  Checkbox,
  message,
  Radio,
  Tree,
  Tag,
  Modal,
  Tabs,
  Card,
  Select,
  Spin,
} from 'antd';

import { connect } from 'dva';
import { formatTreeData } from '@/utils/tools';
import { history } from 'umi';
import {
  getOrgTree,
  getMenuByScope,
  saveRole,
  updateRole,
  roleDetailsById,
} from '@/services/userControl';

import { orgGetOne } from '@/services/common';

import styles from './index.less';

const RoleAddPage = (props: any) => {
  const {
    state: { pageType, roleId },
  } = props.location;
  const { roleStatusMap } = props;
  console.log(pageType, roleId, roleStatusMap);
  const formRef = useRef<any>();
  const [departmentTree, setdepartmentTree] = useState([]);
  const [initialValues, setinitialValues] = useState({});
  const [manageCheckedKeys, setmanageCheckedKeys] = useState([]);
  const [departmentList, setDepartmentList] = useState([]);
  const [functionAthorization, setfunctionAthorization] = useState([]);
  const [functionAuthorizationShow, setfunctionAuthorizationShow] = useState(
    false,
  );
  const [formDisabled, setformDisabled] = useState<boolean | undefined>(false);

  useEffect(() => {
    initPageData();
  }, []);
  const initPageData = async () => {
    await getDepartmentList();
    if (pageType !== 'add') {
      const roleDetails = await roleDetailsById(roleId);
      await getButtonTreeData([roleId]);
      console.log(roleDetails);
      formRef.current.setFieldsValue(roleDetails.data);
    }
  };
  const getDepartmentList = async () => {
    // 根据接口获取值
    const res = await orgGetOne({ isScope: 1 });
    setDepartmentList(res?.data);
  };
  const changeOrg = (id) => {
    if (pageType === 'add') {
      getButtonTreeData([id]);
    }
  };
  const getNodeById = (id, treeData) => {
    for (const item of treeData) {
      console.log(item);
      if (id === item.id) {
        return item;
      }
      if (item.children) {
        let lastData: any = getNodeById(id, item.children);
        if (lastData) {
          return lastData;
        }
      }
    }
  };

  const saveData = async () => {
    try {
      const values = await formRef.current.validateFields();
      const { description, name, status, organizationId } = values;
      let lastData = {
        description,
        featureResourceId: getAllKeys(),
        name,
        organizationId,
        status,
      };
      console.log(lastData);
      let saveRes;
      if (pageType === 'add') {
        saveRes = await saveRole(lastData);
      } else {
        saveRes = await updateRole({ ...lastData, id: roleId });
      }
      console.log(saveRes);
      if (saveRes.code === 200) {
        message.success('保存成功');
        setTimeout(() => {
          history.push({
            pathname: '/features/userPermission/role',
          });
        }, 1000);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  const tabsChange = (activeKey: string) => {
    console.log(activeKey);
  };

  const getButtonTreeData = async (checkedKeys) => {
    let params = {
      contain: 2,
      idList: checkedKeys,
      idType: pageType === 'add' ? 2 : 3,
      scope: 2,
    };
    const res = await getMenuByScope(params);
    console.log('getMenuByScope', res.data);
    setfunctionAthorization(formatTabTreeData(res?.data));
    setfunctionAuthorizationShow(true);
  };
  const formatTabTreeData = (data) => {
    let obj = {};
    for (const item of data) {
      obj[item.id] = {
        checkedKeys: getTreeCheckKeysByFlag([item]),
        treeData: formatTreeData([item]),
        name: item.name,
      };
    }
    return obj;
  };
  const getAllKeys = () => {
    let keys = [];
    for (const item of Object.entries(functionAthorization)) {
      keys.push(...item[1].checkedKeys);
    }
    return keys;
  };
  const getTreeCheckKeysByFlag = (treeData: any[]) => {
    let arr: string[] | number[] = [];
    const _addIDFunction = (_treeData: any[]) => {
      for (const item of _treeData) {
        if (item.flag && !item.children) {
          arr.push(item.id);
        }
        if (item.children) {
          _addIDFunction(item.children);
        }
      }
    };
    _addIDFunction(treeData);
    
    return arr;
  };

  return (
    <>
      <Card title="基本信息" bordered={false}>
        <Form ref={formRef} initialValues={initialValues}>
          <div className={styles.formContainer}>
            <div className={styles.flexRow}>
              <Form.Item
                name="name"
                label="角色名称"
                rules={[{ required: true, message: '请输入角色名称!' }]}
              >
                <Input
                  disabled={pageType === 'details'}
                  placeholder="请输入角色名称"
                ></Input>
              </Form.Item>
              <Form.Item name="description" label="角色描述">
                <Input disabled={pageType === 'details'}></Input>
              </Form.Item>
            </div>
            <div className={styles.flexRow}>
              <Form.Item
                name="organizationId"
                label="归属机构"
                rules={[{ required: true, message: '请选择归属机构!' }]}
              >
                <Select
                  disabled={pageType !== 'add'}
                  placeholder="请选择归属机构"
                  onChange={changeOrg}
                >
                  {departmentList.map((item: any) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态!' }]}
              >
                <Radio.Group disabled={pageType === 'details'}>
                  {Object.entries(roleStatusMap).map((item) => (
                    <Radio key={item[0]} value={+item[0]}>
                      {item[1]}
                    </Radio>
                  ))}
                </Radio.Group>
              </Form.Item>
            </div>
          </div>
        </Form>
      </Card>
      <Card title={'功能授权'} bordered={false}>
        <div className={styles.authorizationContainer}>
          {functionAuthorizationShow ? (
            <Tabs onChange={tabsChange}>
              {Object.entries(functionAthorization).length > 0 &&
                Object.entries(functionAthorization).map((item) => (
                  <Tabs.TabPane tab={item[1].name} key={item[0]}>
                    <div className={styles.treeContainer}>
                      <div>
                        <Card title={item[1].name} bordered={false}>
                          <Tree
                            style={{ height: '280px', overflowY: 'auto' }}
                            checkable
                            disabled={pageType === 'details'}
                            defaultCheckedKeys={item[1].checkedKeys}
                            onCheck={(
                              checkedKeysValue: any,
                              checkedNodes: any,
                            ) => {
                              let lastCheckedKeys = [
                                ...checkedKeysValue,
                                ...checkedNodes.halfCheckedKeys,
                              ];
                              console.log(lastCheckedKeys);
                              setfunctionAthorization({
                                ...functionAthorization,
                                [item[0]]: {
                                  ...functionAthorization[item[0]],
                                  checkedKeys: lastCheckedKeys,
                                },
                              });
                            }}
                            treeData={item[1].treeData}
                          />
                        </Card>
                      </div>
                    </div>
                    {/* {JSON.stringify(item.children)} */}
                  </Tabs.TabPane>
                ))}
            </Tabs>
          ) : (
            <span style={{ color: 'red' }}>请选择归属机构才能进行功能授权</span>
          )}
        </div>
        <div className={styles.footBtnGroup}>
          <Button
            onClick={() => {
              history.go(-1);
            }}
          >
            返回
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            onClick={saveData}
            style={{ marginLeft: '10px' }}
            disabled={pageType === 'details'}
          >
            保存并提交
          </Button>
        </div>
      </Card>
    </>
  );
};
const mapStateToProps = (state: any) => {
  return {
    roleStatusMap: state.common.status,
  };
};
export default connect(mapStateToProps)(RoleAddPage);
